/*******************************************************************************
 * Copyright (c) 2012 laurent barbisan.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    laurent barbisan - initial API and implementation
 *******************************************************************************/ 

package fr.free.hd.servers.android.geonaute.connector;

import java.util.ArrayList;
import java.util.List;

import net.smartam.leeloo.client.OAuthClient;
import net.smartam.leeloo.client.URLConnectionClient;
import net.smartam.leeloo.client.request.OAuthClientRequest;
import net.smartam.leeloo.client.response.OAuthJSONAccessTokenResponse;
import net.smartam.leeloo.common.exception.OAuthProblemException;
import net.smartam.leeloo.common.exception.OAuthSystemException;
import net.smartam.leeloo.common.message.types.GrantType;

import com.isobar.isohealth.GraphConstants;

import android.app.ListActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import fr.free.hd.servers.android.geonaute.connector.model.Track;

public class USBActivity extends ListActivity {

	/**
	 * Log ID
	 */
	private static final String LOG_TAG = "USBActivity";	
	
	final static LoadTrackInfoParams params = new LoadTrackInfoParams();
	final ArrayList<Track> tracks = new ArrayList<Track>();

	private ListView lv;
	
	 
	@Override
    protected void onStart()
    {
		super.onStart();
		
		UsbManager usbManager = (UsbManager) getSystemService(USB_SERVICE);
		UsbDevice usbDevice = this.getIntent().getParcelableExtra(UsbManager.EXTRA_DEVICE);

		lv = getListView();
        lv.setTextFilterEnabled(true);
        lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
	    
        ArrayAdapter<Track> adapter = new ArrayAdapter<Track>(this, R.layout.track_row,R.id.UpdateNameText, tracks);
		setListAdapter(adapter);
		
	    if (usbDevice != null)
			Log.i(LOG_TAG, "device found");
		else
			Log.e(LOG_TAG, "device not found");
		
	   params.setUsbDevice(usbDevice);
	   params.setUsbManager(usbManager);
	   params.setPreferences(this.getSharedPreferences(MainMenuActivity.PREFS_TOKEN, MODE_PRIVATE));
	   params.setAdapter(adapter);
	   
	   new LoadTrackInfoTask().execute(params);
		
		final Button button = (Button) findViewById(R.id.button);
		button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				ArrayList<Track> selectedTracks = new ArrayList<Track>();
		        SparseBooleanArray checkedItems = lv.getCheckedItemPositions();
		            for (int i=0; i<checkedItems.size(); i++) {
		                if (checkedItems.valueAt(i)) {
		                    selectedTracks.add(tracks.get(checkedItems.keyAt(i)));
		                }
		            }
	        	USBActivity.params.setTrackIds(selectedTracks);
		        
				try {				
						OAuthClientRequest request = OAuthClientRequest
								.authorizationLocation(GraphConstants.AUTH_URL)
								.setClientId(GraphConstants.CLIENT_ID)
								.setRedirectURI(GraphConstants.REDIRECT_URI)
								.buildQueryMessage();

						Intent intent = new Intent(Intent.ACTION_VIEW,
								Uri.parse(request.getLocationUri()
										+ "&response_type=code"));
						startActivity(intent);
				} catch (OAuthSystemException e) {
					Log.e(LOG_TAG, "Unable to get credentials from Run Keeper : " + e.getMessage());
				}
				
				
			}
		});
    }	
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.usb);
    }
}
